<?php
/**
 * 销售物料库存Lib类
 * @author xiayuanjun@shopex.cn
 * @version 1.0
 */
class material_sales_material_stock{

    function __construct(){
        $this->_salesMaterialObj = app::get('material')->model('sales_material');
        $this->_salesBasicMaterialObj = app::get('material')->model('sales_basic_material');
        $this->_basicMaterialStockObj = app::get('material')->model('basic_material_stock');
    }

    /**
     *
     * 根据销售物料绑定基础物料计算可用库存
     * @param Int $sm_id 销售物料id
     * @return Int $bm_bind_abled_store 可用库存
     */
    public function getSalesMStockById($sm_id){
        $salesMaterialInfo = $this->_salesMaterialObj->getList('sm_id,shop_id,is_bind,sales_material_type',array('sm_id'=>$sm_id), 0, 1);
        if($salesMaterialInfo){
            //已绑定的才有映射关系有库存
            if($salesMaterialInfo[0]['is_bind'] == 1){
                $salesBasicBindInfo = $this->_salesBasicMaterialObj->getList('sm_id,bm_id,number',array('sm_id'=>$sm_id), 0, -1);
                foreach($salesBasicBindInfo as $k => $bindInfo){
                    $bm_ids[] = $bindInfo['bm_id'];
                    $bm_combine_items[$bindInfo['bm_id']] = $bindInfo['number'];
                }

                $bmStoreInfo = $this->_basicMaterialStockObj->getList('bm_id,store,store_freeze',array('bm_id'=>$bm_ids));
                foreach($bmStoreInfo as $k => $storeInfo){
                    $tmp_abled_store =  ($storeInfo['store']-$storeInfo['store_freeze']) > 0 ? ($storeInfo['store']-$storeInfo['store_freeze']) : 0;
                    $bm_bind_abled_store[] = $tmp_abled_store > 0 ? floor($tmp_abled_store/$bm_combine_items[$storeInfo['bm_id']]) : 0;
                }
                //升序排列
                sort($bm_bind_abled_store);
                return $bm_bind_abled_store[0];
            }
        }
        return 0;
    }

}